package sources;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.RecordControl;

public class MicrophoneSource extends RandomSource {

	private Player player = null;
	private RecordControl recordControl = null;
	private ByteArrayOutputStream outStream = null;
	private static final int DURATION = 100;
	
	public String getSourceName() {
		return "Microphone Source";
	}

	protected void generateNext() {
		recordFor(DURATION);
		byte[] output = outStream.toByteArray();
		int nextInt = 0;
		for(int i = 0; i < output.length; i++){
			nextInt = nextInt ^ ((0xFF & output[i]) << ((i % 4) * 8));
		}
		if(nextInt!=1296116593){
			addRawData(nextInt);
			addToPools(nextInt);
		}
	}

	private void recordFor(long duration) {
		outStream = new ByteArrayOutputStream();
		recordControl.setRecordStream(outStream);
		recordControl.startRecord();
		startPlayer();
		beginRecording(duration);
		commitRrecording();
	}

	private void commitRrecording() {
		try {
			recordControl.commit();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void beginRecording(long i) {
		try {
			Thread.sleep(i);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void startPlayer() {
		try {
			player.start();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void openResources() {
		try {
			player = Manager.createPlayer("capture://audio");
			player.realize();
			recordControl = (RecordControl)player.getControl("RecordControl");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void closeResources() {
		player.close();
	}

}
